package com.elitel.frame.web.cfgsiminfo.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.elitel.common.utils.StringUtils;
import com.elitel.common.utils.SysUserUtils;
import com.elitel.common.utils.UUIDUtil;
import com.elitel.frame.base.service.SysPrjServiceService;
import com.elitel.frame.main.dao.SysPrjserviceMapper;
import com.elitel.frame.main.entity.SysPrjservice;
import com.elitel.frame.web.cfgqueryfield.dao.CfgQueryFieldDao;
import com.elitel.frame.web.cfgqueryfield.entity.CfgQueryField;
import com.elitel.frame.web.cfgsiminfo.dao.CfgSimInfoDao;
import com.elitel.frame.web.cfgsiminfo.dao.CfgSimQueryFieldDao;
import com.elitel.frame.web.cfgsiminfo.entity.CfgSimInfo;
import com.elitel.frame.web.cfgsiminfo.entity.CfgSimInfoDTO;
import com.elitel.frame.web.cfgsiminfo.entity.CfgSimQueryField;
import com.elitel.frame.web.cfgsiminfo.entity.CfgSimQueryFieldListDTO;
import com.elitel.frame.web.cfgsiminfo.service.CfgSimInfoService;
import com.elitel.frame.web.cfgsiminfo.service.CfgSimQueryFieldService;
import com.elitel.frame.web.common.idworker.IdWorker;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author mulis
 */
@Service
public class CfgSimInfoServiceImpl implements CfgSimInfoService {
    @Resource
    private CfgSimInfoDao cfgSimInfoDao;
    @Resource
    private CfgSimQueryFieldDao cfgSimQueryFieldDao;
    @Resource
    private CfgSimQueryFieldService cfgSimQueryFieldService;

    @Resource
    private SysPrjserviceMapper sysPrjserviceMapper;

    @Resource
    private SysPrjServiceService sysPrjServiceService;

    @Resource
    private CfgQueryFieldDao queryFieldDao;


    // 将纳管服务的参数写到参数列表中
    public void copyParamList() {
        List<CfgSimInfo> cfgSimInfos = cfgSimInfoDao.selectList(null);
        List<CfgSimInfo> resList = cfgSimInfos.stream().filter(cfgSimInfo -> cfgSimInfo.getRequestHeader() != null && !cfgSimInfo.getRequestHeader().isEmpty()).collect(Collectors.toList());

        List<CfgSimQueryField> cfgSimQueryFields = cfgSimQueryFieldDao.selectList(null);
        List<CfgQueryField> list = new ArrayList<>();
        for (CfgSimQueryField simQueryField : cfgSimQueryFields) {
            CfgQueryField queryField = new CfgQueryField();
            queryField.setGuid(IdWorker.createStrId());
            queryField.setServiceid(simQueryField.getServiceId());
            queryField.setServicetype(10);
            queryField.setQueryorder(1);
            queryField.setShowtype(0);
            queryField.setRemark("");
            queryField.setCreatedate(LocalDateTime.now());
            queryField.setCreateuser(SysUserUtils.getLoginAccount());
            queryField.setEnumvalue("");
            queryField.setFieldaddonsguid("");
            queryField.setParametercode(simQueryField.getNewFieldCode());
            queryField.setParametercondition("");
            queryField.setGrade("");
            queryField.setParametertype(1);
            queryField.setParametervalue(simQueryField.getDefaultValue());
            queryField.setParamformat("String");
            queryField.setRequiredFlag("0");
            queryField.setParametername(simQueryField.getNewFieldName());
            queryField.setExt1(simQueryField.getParamType() + "");
            queryField.setMetaFieldCode(simQueryField.getSourceFieldCode());
            list.add(queryField);
        }
        for (CfgSimInfo simInfo : resList) {
            JSONObject header = JSONObject.parseObject(simInfo.getRequestHeader());
            header.forEach((k, v) -> {
                CfgQueryField queryField = new CfgQueryField();
                queryField.setGuid(IdWorker.createStrId());
                queryField.setServiceid(simInfo.getServiceId());
                queryField.setServicetype(10);
                queryField.setQueryorder(1);
                queryField.setShowtype(0);
                queryField.setRemark("");
                queryField.setCreatedate(LocalDateTime.now());
                queryField.setCreateuser(SysUserUtils.getLoginAccount());
                queryField.setEnumvalue("");
                queryField.setFieldaddonsguid("");
                queryField.setParametercode(k);
                queryField.setParametercondition("");
                queryField.setGrade("");
                queryField.setParametertype(1);
                queryField.setParametervalue(v + "");
                queryField.setParamformat("String");
                queryField.setRequiredFlag("0");
                queryField.setParametername(k);
                queryField.setExt1("2");
                queryField.setMetaFieldCode(k);
                list.add(queryField);
            });
        }
        queryFieldDao.insertBatch(list);
    }

    @Override
    public int deleteByPrimaryKey(String infoId) {
        return cfgSimInfoDao.deleteByPrimaryKey(infoId);
    }

    @Override
    public int insert(CfgSimInfo record) {
        return cfgSimInfoDao.insert(record);
    }

    @Override
    public int insertSelective(CfgSimInfo record) {
        return cfgSimInfoDao.insertSelective(record);
    }

    @Override
    public CfgSimInfo selectByPrimaryKey(String infoId) {
        return cfgSimInfoDao.selectByPrimaryKey(infoId);
    }

    @Override
    public int updateByPrimaryKeySelective(CfgSimInfo record) {
        return cfgSimInfoDao.updateByPrimaryKeySelective(record);
    }

    @Override
    public int updateByPrimaryKey(CfgSimInfo record) {
        return 0;
    }

    /**
     * 保存服务信息
     *
     * @param dto
     * @return
     */

    @Override
    @Transactional(rollbackFor = Exception.class)
    public CfgSimInfoDTO save(CfgSimInfoDTO dto) {
        this.check(dto);
        HashMap<String, String> headerMap = new HashMap<>();
        for (Map<String, String> requestHeader : dto.getRequestHeaders()) {
            headerMap.put(requestHeader.get("key"), requestHeader.get("value"));
        }
        dto.setRequestHeader(JSONObject.toJSONString(headerMap));
        String username = SysUserUtils.getLoginAccount();
        Date date = new Date();

        // 1.查询服务信息是否存在
        SysPrjservice sysPrjservice = new SysPrjservice();
        if (dto.getServiceId() != null) {
            // 2.如果服务信息存在就更新
            sysPrjservice.setGuid(dto.getServiceId());
            sysPrjservice.setServicename(dto.getServicename());
            sysPrjservice.setSysDataLabelId(dto.getSysDataLabelId());
            sysPrjservice.setApiPath(dto.getApiPath());
            // 更新服务基本信息
            sysPrjserviceMapper.updateByPrimaryKeySelective(sysPrjservice);
            dto.setUpdatedTime(date);
            dto.setUpdatedUser(username);
            // 更新纳管服务基本信息
            this.cfgSimInfoDao.updateByPrimaryKeySelective(dto);
            // 如果不是查询服务的话 就将参数删除掉
            if (!"R".equals(dto.getOptType())) {
                cfgSimQueryFieldDao.deleteByServiceId(dto.getServiceId());
            }
        } else {
            // 3.如果服务信息不存在就新增
            String serviceId = UUIDUtil.randomUUID();
            sysPrjservice.setGuid(serviceId);
            sysPrjservice.setPcode(dto.getPcode());
            sysPrjservice.setServicetype(dto.getServicetype());
            sysPrjservice.setServicecode(dto.getServicecode());
            sysPrjservice.setCreatedate(date);
            sysPrjservice.setCreateuser(username);
            sysPrjservice.setServicename(dto.getServicename());
            sysPrjservice.setStatus(1);
            sysPrjservice.setSysDataLabelId(dto.getSysDataLabelId());
            sysPrjservice.setApiPath(dto.getApiPath());
            sysPrjserviceMapper.insertSelective(sysPrjservice);
            dto.setInfoId(UUIDUtil.randomUUID());
            dto.setServiceId(serviceId);
            dto.setCreatedUser(username);
            dto.setCreatedTime(date);
            dto.setUpdatedUser(username);
            dto.setUpdatedTime(date);
            this.cfgSimInfoDao.insertSelective(dto);
        }

        // 保存参数信息
        String serviceId = dto.getServiceId();
        List<CfgSimQueryField> paramList = dto.getParamList();
        if (paramList != null && !paramList.isEmpty() && serviceId != null && "R".equals(dto.getOptType())) {
            cfgSimQueryFieldService.saveList(new CfgSimQueryFieldListDTO(serviceId, paramList));
        }
        if (paramList == null || paramList.isEmpty()) {
            cfgSimQueryFieldDao.deleteByServiceId(serviceId);
        }
        return dto;
    }

    @Override
    public CfgSimInfoDTO selectByServiceId(String serviceId) {
        CfgSimInfoDTO cfgSimInfoDTO = this.cfgSimInfoDao.selectByServiceId(serviceId);
        if (cfgSimInfoDTO != null) {
            Map<String, String> requestHeaderMap = JSONObject.parseObject(cfgSimInfoDTO.getRequestHeader(), Map.class);
            ArrayList<Map<String, String>> headers = new ArrayList<>();
            requestHeaderMap.forEach((k, v) -> {
                Map<String, String> headerMap = new HashMap<>();
                headerMap.put("key", k);
                headerMap.put("value", v);
                headers.add(headerMap);
            });
            cfgSimInfoDTO.setRequestHeaders(headers);
        }
        return cfgSimInfoDTO;
    }

    @Override
    public List<CfgSimInfo> selectList(CfgSimInfo cfgSimInfo) {
        return cfgSimInfoDao.selectList(cfgSimInfo);
    }

    private void check(CfgSimInfoDTO dto) {

        StringBuilder errorMsg = new StringBuilder();
        boolean b = this.sysPrjServiceService.serviceCodeExist(dto.getServiceId(), dto.getServicecode());
        if (b) {
            errorMsg.append("服务编码已存在，请重新填写;  ");
        }
        if (StringUtils.isBlank(dto.getServicename())) {
            errorMsg.append("服务名称不能为空;  ");
        }
        if (StringUtils.isBlank(dto.getServicecode())) {
            errorMsg.append("服务ID不能为空;  ");
        }
        if (StringUtils.isBlank(dto.getRequestUrl())) {
            errorMsg.append("请求地址不能为空;  ");
        }
        if (StringUtils.isBlank(dto.getRequestMethod())) {
            errorMsg.append("请求类型不能为空;  ");
        }
        if (StringUtils.isBlank(dto.getContentType())) {
            errorMsg.append("参数内容类型不能为空;  ");
        }
        if (StringUtils.isBlank(dto.getOptType())) {
            errorMsg.append("操作类型不能为空;  ");
        }
        List<Map<String, String>> requestHeaders = dto.getRequestHeaders();
        if (requestHeaders != null && !requestHeaders.isEmpty()) {
            for (int i = 0; i < requestHeaders.size(); i++) {
                Map<String, String> requestHeader = requestHeaders.get(i);
                String key = requestHeader.get("key");
                String value = requestHeader.get("value");
                if (StringUtils.isBlank(key)) {
                    errorMsg.append("第").append(i + 1).append("行请求头标识不能为空;  ");
                }
                if (StringUtils.isBlank(value)) {
                    errorMsg.append("第").append(i + 1).append("行请求头值不能为空;  ");
                }
            }
        }

        List<CfgSimQueryField> paramList = dto.getParamList();
        HashSet<String> paramCode = new HashSet<>();
        HashSet<String> newParamCode = new HashSet<>();
        for (int i = 0; i < paramList.size(); i++) {
            CfgSimQueryField cfgSimQueryField = paramList.get(i);
            if (StringUtils.isBlank(cfgSimQueryField.getSourceFieldCode())) {
                errorMsg.append("第").append(i + 1).append("行源参数编码").append(cfgSimQueryField.getSourceFieldCode()).append("不能为空;  ");
            } else if (paramCode.contains(cfgSimQueryField.getSourceFieldCode())) {
                errorMsg.append("第").append(i + 1).append("行源参数编码重复;  ");
            } else {
                paramCode.add(cfgSimQueryField.getSourceFieldCode());
            }

            if (StringUtils.isNotBlank(cfgSimQueryField.getNewFieldCode())) {
                if (newParamCode.contains(cfgSimQueryField.getNewFieldCode())) {
                    errorMsg.append("第").append(i + 1).append("行新参数编码").append(cfgSimQueryField.getNewFieldCode()).append("重复;  ");
                } else {
                    newParamCode.add(cfgSimQueryField.getNewFieldCode());
                }
            }
        }

        if (!StringUtils.isBlank(errorMsg.toString())) {
            throw new RuntimeException(errorMsg.toString());
        }
    }
}
